"use strict";

var m_AbilityPanels = []; // created up to a high-water mark, but reused when selection changes

function UpdateAbilityList()
{
	var abilityListPanel1 = $( "#ability_line1" );
	var abilityListPanel2 = $( "#ability_line2" );
	var abilityListPanel3 = $( "#ability_line3" );
	var abilityListPanel4 = $( "#ability_line4" );

	var queryUnit = Players.GetLocalPlayerPortraitUnit();

	// see if we can level up
	var nRemainingPoints = Entities.GetAbilityPoints( queryUnit );
	var bPointsToSpend = ( nRemainingPoints > 0 );
	var bControlsUnit = Entities.IsControllableByPlayer( queryUnit, Game.GetLocalPlayerID() );
	$.GetContextPanel().SetHasClass( "could_level_up", ( bControlsUnit && bPointsToSpend ) );

	// update all the panels
	var nUsedPanels = 0;
	for ( var i = 0; i < 15; ++i )
	{
		var abilityListPanel;
		if (i<=3) abilityListPanel=abilityListPanel1;
		if (i>3&&i<=7) abilityListPanel=abilityListPanel2;
		if (i>7&&i<=11) abilityListPanel=abilityListPanel3;
		if (i>11&&i<=15) abilityListPanel=abilityListPanel4;
		var ability = Entities.GetAbility( queryUnit, i );
		if ( ability == -1 )
			continue;
		if ( Abilities.GetAbilityName(ability)=="attribute_bonus")
			continue;
		if ( Abilities.IsHidden(ability) )
			continue;
		$.Msg(Abilities.GetAbilityName(ability));
		if ( nUsedPanels >= m_AbilityPanels.length )
		{
			// create a new panel
			var abilityPanel = $.CreatePanel( "Panel", abilityListPanel, "" );
			abilityPanel.BLoadLayout( "file://{resources}/layout/custom_game/ability.xml", false, false );
			m_AbilityPanels.push( abilityPanel );
		}

		// update the panel for the current unit / ability
		var abilityPanel = m_AbilityPanels[ nUsedPanels ];
		abilityPanel.data().SetAbility( ability, queryUnit, Game.IsInAbilityLearnMode() );
		
		nUsedPanels++;
	}

	// clear any remaining panels
	for ( var i = nUsedPanels; i < m_AbilityPanels.length; ++i )
	{
		var abilityPanel = m_AbilityPanels[ i ];
		abilityPanel.data().SetAbility( -1, -1, false );
	}
}

(function()
{

	GameEvents.Subscribe( "dota_portrait_ability_layout_changed", UpdateAbilityList );
	GameEvents.Subscribe( "dota_player_update_selected_unit", UpdateAbilityList );
	GameEvents.Subscribe( "dota_player_update_query_unit", UpdateAbilityList );
	GameEvents.Subscribe( "dota_ability_changed", UpdateAbilityList );
	GameEvents.Subscribe( "dota_hero_ability_points_changed", UpdateAbilityList );
	
	UpdateAbilityList(); // initial update
})();